package com.fengdi.book.middle;

import com.fengdi.publicObject.TreeNode;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;

public class DesignProblem {

    public static class Codec {
        private final String NULL="#";
        private final String SPLIT=",";

        // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            StringBuilder sb = new StringBuilder();
            this.serialize(root, sb);
            return sb.toString();
        }

        private void serialize(TreeNode root,StringBuilder sb) {
            if(root == null) {
                sb.append(this.NULL).append(this.SPLIT);
                return;
            }
            sb.append(root.val).append(this.SPLIT);
            serialize(root.left,sb);
            serialize(root.right,sb);
        }

        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            LinkedList<String> nodes = new LinkedList<>();
            Collections.addAll(nodes, data.split(this.SPLIT));

            return deserialize(nodes);
        }

        private TreeNode deserialize(LinkedList<String> nodes) {
            if (nodes.isEmpty()){
                return null;
            }
            String val = nodes.removeFirst();
            if (this.NULL.equals(val)){
                return null;
            }
            TreeNode root = new TreeNode(Integer.parseInt(val));

            root.left = deserialize(nodes);
            root.right = deserialize(nodes);

            return root;
        }
    }

    public static class RandomizedSet {
        private HashSet<Integer> set = new HashSet<>();

        public RandomizedSet() {

        }

        public boolean insert(int val) {
            if(this.set.contains(val)) return false;
            set.add(val);
            return true;
        }

        public boolean remove(int val) {
            if(this.set.contains(val)) {
                this.set.remove(val);
                return true;
            }
            return false;
        }

        public int getRandom() {
            int num = this.set.size();
            int index = (int)(Math.random() * num);
            return this.set.stream().toList().get(index);
        }
    }
}
